﻿namespace Atomic.Plugins.Users.Controllers.Admin
{
    using System.Web.Mvc;

    using Atomic.Logging;
    using Atomic.Exceptions;
    using Atomic.Collections;
    using Atomic.Modules.Security;

    using Atomic.Core.Security;
    
    using Atomic.Mvc.Filters;
    using Atomic.Mvc.Settings;

    using Atomic.Plugins.Users.Models;
    using Atomic.Plugins.Users.Application;
    using Atomic.Plugins.Users.Domain.Admin;
    using Atomic.Plugins.Users.Exceptions;
    

    /// <summary>
    /// 角色管理后台控制器
    /// </summary>
    [Login]
    [AtomicAuthorize(SystemPermissions.IsLoginAdmin)]
    [Layout("_AdminLayout")]
    public class AdminRoleController : Controller
    {
        #region 字段

        /// <summary>
        /// 站点信息。
        /// </summary>
        private readonly ISite _site = null;

        /// <summary>
        /// 角色管理服务。
        /// </summary>
        private readonly IRoleAdminService _roleAdminService = null;

        #endregion

        #region 初始化

        /// <summary>
        /// 初始化角色管理后台控制器。
        /// </summary>
        /// <param name="roleAdminService">用户管理服务。</param>
        public AdminRoleController(IRoleAdminService roleAdminService)
        {
            this._roleAdminService = roleAdminService;

            this._site = SiteFactory.Current;
            this.Logger = LoggerFactory.Current.Create();
        }

        #endregion

        #region 日志

        /// <summary>
        /// 日志工具。
        /// </summary>
        private ILogger Logger { get; set; }

        #endregion

        #region 首页

        /// <summary>
        /// 首页。
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        #endregion

        #region 角色列表

        /// <summary>
        /// 角色列表。
        /// </summary>
        /// <param name="pageIndex">页码。</param>
        /// <returns></returns>
        [AtomicAuthorize(Permissions.Role_IsShowRoleList)]
        public ActionResult List(int pageIndex)
        {
            var items = this._roleAdminService.GetRoles(new PagerParameters(index: pageIndex, size: this._site.PageSize));

            return View(items);
        }

        #endregion

        #region 增加角色

        /// <summary>
        /// 增加角色
        /// </summary>
        /// <returns></returns>
        [AtomicAuthorize(Permissions.Role_Add)]
        public ActionResult Add()
        {
            return View(new AddRoleModel());
        }

        [AtomicAuthorize(Permissions.Role_Add)]
        [HttpPost]
        public ActionResult Add(AddRoleModel addRoleModel)
        {
            if (this.ModelState.IsValid)
            {
                var result = this._roleAdminService.AddRole(addRoleModel);

                if(result == AddRoleStatus.Success)
                {
                    this.Logger.LogInfo("管理员({0})增加角色({1})。", User.Identity.Name, addRoleModel.Id);

                    ViewData["Message"] = "增加角色成功";

                    return this.View("Success");
                }
            }

            return View(addRoleModel);
        }

        #endregion

        #region 编辑角色

        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <param name="roleId">角色编号。</param>
        /// <returns></returns>
        [AtomicAuthorize(Permissions.Role_Edit)]
        public ActionResult Edit(int roleId)
        {
            var role = this._roleAdminService.GetRole(roleId);

            EditRoleModel model = new EditRoleModel();

            if(role == null)
            {
                throw new AtomicException(string.Format("角色编号：{0}，的角色不存在。", roleId));
            }

            model.Id = role.Id;
            model.Name = role.Name;
            model.DisplayName = role.DisplayName;
            model.Type = role.Type;

            return View(model);
        }

        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <param name="roleId">角色编号。</param>
        /// <returns></returns>
        [AtomicAuthorize(Permissions.Role_Edit)]
        [HttpPost]
        public ActionResult Edit(int roleId, EditRoleModel editRoleModel)
        {
            if (this.ModelState.IsValid)
            {
                var result = this._roleAdminService.EditRole(roleId, editRoleModel);

                if (result == EditRoleStatus.Success)
                {
                    this.Logger.LogInfo("管理员({0})编辑角色({1})。", User.Identity.Name, editRoleModel.Id);

                    ViewData["Message"] = "编辑角色成功";

                    return this.View("Success");
                }
            }

            return View(editRoleModel);
        }

        #endregion

        #region 角色授权

        /// <summary>
        /// 角色授权
        /// </summary>
        /// <param name="roleId">角色编号。</param>
        /// <returns></returns>
        [AtomicAuthorize(Permissions.Role_Authorize)]
        public ActionResult Authorize(int roleId)
        {
            var role = this._roleAdminService.GetRole(roleId);

            if(role == null)
            {
                throw new AuthorizeRoleException(string.Format("编号 {0} 的角色不存在。", roleId));
            }

            var permissions = this._roleAdminService.GetPermissions();

            return View(new AuthorizeRoleModel { Role = role, Permissions = permissions });
        }

        /// <summary>
        /// 角色授权
        /// </summary>
        /// <param name="roleId">角色编号。</param>
        /// <param name="authorizeRoleModel">角色授权模型。</param>
        /// <returns></returns>
        [AtomicAuthorize(Permissions.Role_Authorize)]
        [HttpPost]
        public ActionResult Authorize(int roleId, AuthorizeRoleModel authorizeRoleModel)
        {
            if (this.ModelState.IsValid)
            {
                var result = this._roleAdminService.RoleAuthorize(authorizeRoleModel);

                if (result == AuthorizeRoleStatus.Success)
                {
                    this.Logger.LogInfo("管理员({0})对角色({1})重新进行授权。", User.Identity.Name, authorizeRoleModel.Role.Id);

                    ViewData["Message"] = "角色授权成功";

                    return this.View("Success");
                }
            }

            authorizeRoleModel.Role = this._roleAdminService.GetRole(roleId);

            if (authorizeRoleModel.Role == null)
            {
                throw new AuthorizeRoleException(string.Format("编号 {0} 的角色不存在。", roleId));
            }

            authorizeRoleModel.Permissions = this._roleAdminService.GetPermissions();

            return View(authorizeRoleModel);
        }

        #endregion
    }
}